package org.go.work;

import java.util.concurrent.Callable;

import org.go.Go;
import org.go.GoContext;
import org.go.GoContextImpl;
import org.go.log.Log;
import org.go.log.LoggerFactory;
import org.go.scheduler.Scheduler;
import org.go.trigger.Trigger;

/**
 * 
 * @author hejie
 *
 */
public class WorkRunShell implements Runnable, Callable<Boolean> {
	private static final Log LOG = LoggerFactory.getLog(WorkRunShell.class);
	private GoContext context = null;
	private Go go = null;
	private boolean runFlag = true;
	private Trigger trigger;

	public WorkRunShell(Go go, Trigger trigger) throws Exception {
		if (go == null) {
			throw new Exception("the go impl class instance can not be null");
		}
		this.go = go;
		this.trigger = trigger;
	}

	@Override
	public Boolean call() throws Exception {
		try {
			return go.doWork(context);
		} catch (Exception e) {
			LOG.error("{}", e);
			return null;
		}
	}

	public void initialize(Scheduler qs) {
		//try {
		context = new GoContextImpl(go, trigger, qs);
		//qs.getJobGroupNames();
		//	} catch (SchedulerException e) {
		//	e.printStackTrace();
		//}
	}

	public boolean isRun() {
		return runFlag;
	}

	@Override
	public void run() {
		try {
			go.doWork(context);
		} catch (Exception e) {
			LOG.error("{}", e);
			return;
		}
		if (!runFlag) {
			LOG.debug("break");
			//	break;
		}
	}

	public void shutdown() {
		this.runFlag = false;
	}

	//	public void passivate() {
	//
	//	}

	//	protected void begin() throws SchedulerException {
	//
	//	}
	//
	//	protected void complete(boolean successfulExecution) throws SchedulerException {
	//
	//	}
}
